<template>
    <div v-loading="loading">
        <el-card v-loading="loading">
            <template #header>
                <div>添加班级</div>
            </template>
            <el-form ref="addform" :rules="rules" :model="form" label-width="100px" label-position="left">
                <el-form-item label="添加班级" prop="classname">
                    <el-input v-model="form.classname"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="save">保存</el-button>
                    <el-button @click="$router.push({ name: 'ClassIndex' })">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>
<script>
import { mapActions } from "vuex";
export default {
    data() {
        return {
            loading: false,
            form: {},
            rules: {
                classname: [
                    { required: true, message: "班级名不能为空" },
                    {
                        validator: (rule, value, cb) => {
                            if (/^.{2,18}$/.test(value)) {
                                cb();
                            } else {
                                cb(new Error("班级名必须2-18个字符"));
                            }
                        },
                    },
                    {
                        validator: async (rule, value, cb) => {

                            const { data } = await this.exist({
                                field: "classname",
                                value,
                            });
                            if (data) {
                                cb(new Error("用户名重复"));
                            } else {
                                cb();
                            }
                        },
                        trigger: "blur",
                    },
                ],
            },
        };
    },

    created() {
        //  this.save()
    },

    methods: {
        ...mapActions('classes', ['addClasses', 'exist']),
        save() {
            this.loading = true;
            this.$refs.addform.validate(async (valid) => {
                if (valid) {
                    try {
                        await this.addClasses({ classname: this.form.classname });
                        this.$message.success("添加成功");
                        this.$router.push({ name: "ClassIndex" });
                    } catch (error) {
                        this.$message.error(error.response.data.message);
                    }
                }
            });
            this.loading = false
        },
    },
};
</script>
